package com.zxq.factory.decoder.impl;
import com.zxq.factory.decoder.IFieldDecoder;


public class IntDecoder implements IFieldDecoder<Integer> {


    //左高右低
    @Override
    public Integer decoder(byte[] msg) {
        int len = msg.length;
        Integer value = 0;
        Integer radix = 1;
        Integer sum = 0;
        if(msg[0] >= 0) {
            //原码 - 真值
            for (int i = 0; i < len; i++) {
                Integer temp = (msg[len - i - 1] + 256) %256;
                value = temp * radix;
                if (value < 0) {
                    value = value & 0xff;
                }
                sum += value;
                radix = radix * 256;
            }
        } else {
         //补码 -> 反码
            // 补码运算
            int prefix = 0;
            int index = len - 1;
            do{
                if(msg[index] == (byte)0x00) {
                    //0xff进位的时候置为零，下一位加一
                    //  System.out.println("index: " + index + " num:" + buff[index]);
                    msg[index] = (byte) 0xff;
                    prefix = 1;
                    index = index - 1;
                } else {
                    //补码 + 1
                    msg[index] = (byte) (msg[index] + prefix);
                    msg[index] -= 1;
                    break;
                }
            }while (index > 0);
         //反码 - 原码
            for (int i = 0; i < len; i++) {
                msg[i] = (byte) ~msg[i];
            }

            //原码 - 真值
            for (int i = 0; i < len; i++) {
                byte temp = msg[len - i - 1];
                value = temp * radix;
                if (value < 0) {
                    value = value & 0xff;
                }
                sum += value;
                radix = radix * 256;
            }
            sum = -1 * sum;
        }
        return sum;
    }






}
